package com.rjwh.dingdong.client.util;

import android.content.Context;
import android.os.Environment;

import com.rjwh.dingdong.client.constant.LocalConstant;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

public class FileUtils {
    private static Context mContext;
    private static String mSdRootPath;
    private static String mSdAppcache;


    private final static String IMAGE_DIR = "Images";

    private final static String PIC_DIR = "pictures";

    private final static String APK_DIR = "download";


    public final static String TEMPIMAGE_DIR = "tempimage";

    private final static String GAME_DIR = ".game";

    private final static String DRWABOOK_DIR = ".drwabook";

    private final static String DOWNLOAD_DIR = ".download";

    private final static String PUBLIC_RES = "10000";

    public static void initFileManage(Context context) {
        mContext = context;
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            File appDir = new File(Environment.getExternalStorageDirectory(),
                    LocalConstant.CONST_APP_DIR_NAME);
            if (!appDir.exists()) {
                appDir.mkdirs();
            }
            mSdRootPath = appDir.getPath() + File.separator;
        }
        mSdAppcache = mContext.getCacheDir().getPath() + File.separator;
    }

    public static String getDirectory() {
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return mSdRootPath;
        }
        return mSdAppcache;

    }


    public static String getAPKStorageDirectory() {
        File file = new File(getDirectory() + APK_DIR);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file.getPath() + File.separator;
    }

    public static String getTempImageStorageDirectory() {
        File file = new File(getDirectory() + TEMPIMAGE_DIR);
        if (!file.exists()) {
            file.mkdirs();
        }
        File nomedia = new File(file + File.separator + ".nomedia");
        if (!nomedia.exists()) {
            try {
                nomedia.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file.getPath() + File.separator;
    }

    public static String getPicStorageDirectory() {
        File file = new File(getDirectory() + PIC_DIR);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file.getPath() + File.separator;
    }

    public static String getGameDirectory() {
        File file = new File(getDirectory() + GAME_DIR);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file.getPath() + File.separator;
    }

    public static String getDrwabookDirDirectory() {
        File file = new File(getDirectory() + DRWABOOK_DIR);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file.getPath() + File.separator;
    }


    public static String getPublicDirectory() {
        File file = new File(getDrwabookDirDirectory() + PUBLIC_RES);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file.getPath() + File.separator;
    }

    public static String getDownloadDirectory() {
        File file = new File(getDirectory() + DOWNLOAD_DIR);
        if (!file.exists()) {
            file.mkdirs();
        }
        return file.getPath() + File.separator;
    }

    /**
     * 复制单个文件
     *
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param
     * @return boolean
     */
    public static boolean copyFile(String oldPath) {
        boolean isok = true;
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { // 文件存在时
                InputStream inStream = new FileInputStream(oldPath); // 读入原文件
                FileOutputStream fs = new FileOutputStream(
                        getPicStorageDirectory() + File.separator + oldPath
                                + ".jpg");
                byte[] buffer = new byte[1024];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; // 字节数 文件大小
                    // System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                fs.flush();
                fs.close();
                inStream.close();
            } else {
                isok = false;
            }
        } catch (Exception e) {
            // System.out.println("复制单个文件操作出错");
            // e.printStackTrace();
            isok = false;
        }
        return isok;

    }

    /**
     * 复制整个文件夹内容
     *
     * @param oldPath String 原文件路径 如：c:/fqf
     * @param newPath String 复制后路径 如：f:/fqf/ff
     * @return boolean
     */
    public static boolean copyFolder(String oldPath, String newPath) {
        boolean isok = true;
        try {
            (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }

                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath
                            + "/" + (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {// 如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
                }
            }
        } catch (Exception e) {
            isok = false;
        }
        return isok;
    }

    /**
     * 获取文件名
     *
     * @param @param  pathandname
     * @param @return
     * @return String
     * @throws
     * @Title: getFileName
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @history 1.YYYY-MM-DD
     * author:
     * description:
     */
    public static String getFileName(String pathandname) {

        int start = pathandname.lastIndexOf("/");
        int end = pathandname.lastIndexOf(".");
        if (start != -1 && end != -1) {
            return pathandname.substring(start + 1, end);
        } else {
            return null;
        }

    }

    /**
     * 获取Iamges缓存文件名
     *
     * @param @param  pathandname
     * @param @return
     * @return String
     * @throws
     * @Title: getFileName
     * @Description: TODO(这里用一句话描述这个方法的作用)
     * @history 1.YYYY-MM-DD
     * author:
     * description:
     */
    public static String getCacheFileName(String pathandname) {

        int start = pathandname.lastIndexOf("/");
        if (start != -1) {
            return pathandname.substring(start + 1);
        } else {
            return null;
        }

    }

    /**
     * 递归删除文件和文件夹
     *
     * @param file 要删除的根目录
     */
    public static void deleteFile(File file) {
        if (file.isFile()) {
            file.delete();
            return;
        }
        if (file.isDirectory()) {
            File[] childFile = file.listFiles();
            if (childFile == null || childFile.length == 0) {
                file.delete();
                return;
            }
            for (File f : childFile) {
                deleteFile(f);
            }
            file.delete();
        }
    }
}
